package com.authine.cloudpivot.controller;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.enums.status.WorkflowInstanceStatus;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.ext.service.ipml.SyncKeyProjectServiceImpl;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.Result;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;

@RestController
@RequestMapping("/api/extresident")
@Slf4j
public class ExtResidentController extends BaseController {

    @Autowired
    private JPANativeQuery jpaNativeQuery;

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    SyncKeyProjectServiceImpl syncKeyProjectService;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    private static final String SCHMEA_CODE = "difficultGroupsInsurance";

    private static final String RESIDENT_CODE = "resident";

    private static final String HOUSE_CODE = "house";

    private static final String BUSINESS_CODE = "business";


    @PostMapping("/updateResident")
    @Transactional
    public Result updateResident(@RequestBody JSONObject object) {
        if (StringUtils.isBlank(object.getString("id"))) {
            return Result.fail("参数不能为空");
        }
        String id = object.getString("id");
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SCHMEA_CODE, id);
        if (Objects.isNull(bizObject)) {
            return Result.fail("未找到模型");
        }
        Map<String, Object> relevrelevanceResident = bizObject.getMap("relevanceResident");
        Map<String, Object> relevanceHouse = bizObject.getMap("relevanceHouse");
        String residentName = (String) bizObject.get("residentName");
        String personnelNature = (String) bizObject.get("personnelNature");
        String mobile = (String) bizObject.get("mobile");
        String idCard = (String) bizObject.get("IDCard");
        if (MapUtils.isEmpty(relevrelevanceResident)) {
            Map<String, Object> data = new HashMap<>();
            data.put("residentName", residentName);
            data.put("telephone", mobile);
            data.put("IDNumber", idCard);
            if (MapUtils.isNotEmpty(relevanceHouse)) {
                data.put("relevanceHouse", relevanceHouse);
            }
//            StringJoiner sj= new StringJoiner(";");
//            sj.add(personnelNature).add("普通居民");
            data.put("personnelNature", personnelNature);
            data.put("belongJd", bizObject.get("belongJd"));
            data.put("belongSq", bizObject.get("belongSq"));
            BizObjectModel resident = new BizObjectModel(RESIDENT_CODE, data, Boolean.TRUE);
            resident.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            resident.setSequenceNo(UUID.fastUUID().toString());
            bizObjectFacade.saveBizObjectModel(bizObject.getCreater().getId(), resident, null);
            Map<String, Object> residentmap = new HashMap<>();
            residentmap.put("schemaCode", "resident");
            residentmap.put("propertyType", BizPropertyType.SHORT_TEXT);
            residentmap.put("displayCode", "name");
            residentmap.put("name", residentName);
            residentmap.put("id", resident.getId());
            bizObject.put("relevanceResident", residentmap);
            String sql = String.format("update  `iknn4_difficultgroupsinsurance` set relevanceResident = '%s'  where id = '%s'", resident.getId(), bizObject.getId());
            Query nativeQuery = entityManager.createNativeQuery(sql);
            nativeQuery.executeUpdate();

        } else {
            BizObjectCreatedModel resident = bizObjectFacade.getBizObject(RESIDENT_CODE, relevrelevanceResident.get("id").toString());
            if (Objects.nonNull(resident)) {
                String nature = (String) resident.get("personnelNature");
                String queyrsf = "select name from ybjzsf";
                List<Map<String, String>> list = jpaNativeQuery.getList(queyrsf, null, null);
                Map<String, String> stringStringMap = list.get(0);
                String sf = stringStringMap.get("name");
                String[] sfList = sf.split(";");
                if (StringUtils.isNotBlank(personnelNature)) {
                    String[] split = personnelNature.split(";");
                    Set<String> setB = new HashSet<>(Arrays.asList(split));
                    List<String> missing = new ArrayList<>();
                    for (String s : sfList) {
                        if (!setB.contains(s)) {
                            missing.add(s);
                        }
                    }
                    String[] split1 = nature.split(";");
                    Set<String> natures = new HashSet<>(Arrays.asList(split1));
                    for (String s : missing) {
                        if (natures.contains(s)) {
                            natures.remove(s);
                        }
                    }
                    StringJoiner joiner = new StringJoiner(";");
                    for (String s : natures) {
                        joiner.add(s);
                    }
                    String newnature = joiner.toString();
                    for (String s : split) {
                        if (!newnature.contains(s)) {
                            if (StringUtils.isNotBlank(newnature)) {
                                newnature = newnature + ";" + s;
                            } else {
                                newnature = s;
                            }
                        }
                    }
                    resident.put("personnelNature", newnature);
                }
                if (MapUtils.isNotEmpty(relevanceHouse)) {
                    resident.put("relevanceHouse", relevanceHouse);
                }
                if (StringUtils.isNotBlank(residentName)) {
                    resident.put("residentName", residentName);
                }
                if (StringUtils.isNotBlank(mobile)) {
                    resident.put("telephone", mobile);
                }
                if (StringUtils.isNotBlank(idCard)) {
                    resident.put("IDNumber", idCard);
                }
                bizObjectFacade.saveBizObject(resident.getCreater().getId(), resident, Boolean.TRUE);
            }
        }

        return Result.ok();
    }

    /**
     * 更新居民 身份证
     *
     * @param object
     * @return
     */
    @PostMapping("/updateResidentById")
    public Result updateResidentById(@RequestBody JSONObject object) {
        if (object.isEmpty()) {
            return Result.fail("参数不能为空");
        }
        String idNumber = object.getString("IDNumber");
        String sql = String.format("SELECT id FROM `iknn4_resident` where IDNumber = '%s' and ifnull(dataStatus,'') <> '废弃'", idNumber);
        List<Map<String, Object>> list = jpaNativeQuery.getList(sql, null, null);
        String userId = getUserId();
        if (CollectionUtils.isEmpty(list)) {
            Map<String, Object> data = new HashMap<>();
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    data.put(key, object.get(key));
                }
            }
            BizObjectModel resident = new BizObjectModel(RESIDENT_CODE, data, Boolean.TRUE);
            resident.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            resident.setSequenceNo(UUID.fastUUID().toString());
            bizObjectFacade.saveBizObjectModel(userId, resident, null);
            return Result.ok();
        }
        for (Map<String, Object> map : list) {
            BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(RESIDENT_CODE, (String) map.get("id"));
            String sf = bizObject.getString("personnelNature");
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    bizObject.put(key, object.get(key));
                }
            }
            if (StringUtils.isNotBlank(sf)) {
                String[] sfList = sf.split(";");
                String personnelNature = object.getString("personnelNature");
                if (StringUtils.isNotBlank(personnelNature)) {
                    String[] split = personnelNature.split(";");
                    Set<String> setB = new HashSet<>(Arrays.asList(split));
                    List<String> missing = new ArrayList<>();
                    for (String s : sfList) {
                        if (!setB.contains(s)) {
                            missing.add(s);
                        }
                    }
                    String[] split1 = sf.split(";");
                    Set<String> natures = new HashSet<>(Arrays.asList(split1));
                    for (String s : missing) {
                        if (natures.contains(s)) {
                            natures.remove(s);
                        }
                    }
                    StringJoiner joiner = new StringJoiner(";");
                    for (String s : natures) {
                        joiner.add(s);
                    }
                    String newnature = joiner.toString();
                    for (String s : split) {
                        if (!newnature.contains(s)) {
                            if (StringUtils.isNotBlank(newnature)) {
                                newnature = newnature + ";" + s;
                            } else {
                                newnature = s;
                            }
                        }
                    }
                    bizObject.put("personnelNature", newnature);
                }
            }
            bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);
        }
        return Result.ok();
    }

    @GetMapping("/updateCzStatus")
    public Result updateCzStatus(@RequestParam("id") String id) {
        if (StringUtils.isBlank(id)) {
            return Result.fail("参数不能为空");
        }
        syncKeyProjectService.updateStatus(id);
        return Result.ok();
    }

    /**
     * 更新房屋预计人天
     *
     * @param object
     * @return
     */
    @PostMapping("/updateHouseById")
    public Result updateHouseById(@RequestBody JSONObject object) {
        return updateForTable(object, HOUSE_CODE);
    }

    /**
     * 更新商企 统一社会信用代码 办理单位
     *
     * @param object
     * @return
     */
    @PostMapping("/updateBusinessById")
    public Result updateBusinessById(@RequestBody JSONObject object) {
        if (object.isEmpty()) {
            return Result.fail("参数不能为空");
        }
        String creditCode = object.getString("creditCode");
        String sql = String.format("SELECT * FROM `iknn4_business` where creditCode = '%s'  and ifnull(dataStatus,'') <> '废弃'", creditCode);
        List<Map<String, Object>> list = jpaNativeQuery.getList(sql, null, null);
        String userId = getUserId();
        if (CollectionUtils.isEmpty(list)) {
            Map<String, Object> data = new HashMap<>();
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    data.put(key, object.get(key));
                }
            }
            BizObjectModel resident = new BizObjectModel(BUSINESS_CODE, data, Boolean.TRUE);
            resident.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            resident.setSequenceNo(UUID.fastUUID().toString());
            bizObjectFacade.saveBizObjectModel(userId, resident, null);
            return Result.ok();
        }
        for (Map<String, Object> map : list) {
            BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(BUSINESS_CODE, (String) map.get("id"));
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    bizObject.put(key, object.get(key));
                }
            }
            bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);
        }
        return Result.ok();
    }

    public Result updateForTable(JSONObject object, String sheetCode) {
        if (object.isEmpty()) {
            return Result.fail("参数不能为空");
        }
        String userId = getUserId();
        String id = object.getString("id");
        if (StringUtils.isBlank(id)) {
            Map<String, Object> data = new HashMap<>();
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    data.put(key, object.get(key));
                }
            }
            BizObjectModel resident = new BizObjectModel(sheetCode, data, Boolean.TRUE);
            resident.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            resident.setSequenceNo(UUID.fastUUID().toString());
            bizObjectFacade.saveBizObjectModel(userId, resident, null);
            return Result.ok();
        }
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(sheetCode, id);
        if (Objects.isNull(bizObject)) {
            //新建
            Map<String, Object> data = new HashMap<>();
            for (String key : object.keySet()) {
                if (!key.equals("id")) {
                    data.put(key, object.get(key));
                }
            }
            BizObjectModel resident = new BizObjectModel(sheetCode, data, Boolean.TRUE);
            resident.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            resident.setSequenceNo(UUID.fastUUID().toString());
            bizObjectFacade.saveBizObjectModel(userId, resident, null);
            return Result.ok();
        }

        for (String key : object.keySet()) {
            if (!key.equals("id")) {
                bizObject.put(key, object.get(key));
            }
        }
        bizObjectFacade.saveBizObject(bizObject.getCreater().getId(), bizObject, Boolean.TRUE);
        return Result.ok();
    }


}
